import pd from '/api/productData.js';
import cd from '/api/cartData.js';
import ud from '/api/usrData.js';
import hs from '/components/head-search.js';
import rfb from '/components/right-fixed-bar.js';
(() => {
    $('.header-top-nav-wrap').load('/components/head-nav.html');
    $('.head').load('/components/head-search.html', () => {
        $('.search-btn').on('click', function() {
            const key = $('.search-key').val();

            // console.log(key ? "q=" + key : "title=" + $('.search-key').attr('placeholder'));
            location.href = '/pages/list.html?' + (key ? "q=" + key : "title=" + $('.search-key').attr('placeholder'));
        })
    });
    $('.bottom-footer-wrap').load('/components/bottom-footer.html');
    $('.right-bar').load('/components/right-fixed-bar.html');

    generateMainheadNav();
    generateMainBigSwiper();
    generateMainLittleSwiper();
    getRealKey();
    // getRealKeys()



})()

/* 随机生成关键字填充数据 */
function getRealKey() {
    axios.get('http://localhost:3000/realKeys')
        .then(res => {
            const data = res.data;
            generateDiscount($('.main-discount'));
            generateHotList(getRandKey(data));
            $('.search-key').attr('placeholder', getRandKey(data));
            generateCategory(10);
        })

}

function getRandKey(data) {
    return data[parseInt(Math.random() * data.length)];
}

/* 获取可用关键字
function getRealKeys() {
    axios.get('http://localhost:3000/allTitle')
        .then(res => {
            let realkeys = [];
            res.data.forEach(el => {
                axios.get('http://localhost:3000/plist?title=' + el)
                    .then(r => {
                        if (JSON.stringify(r.data) != '[]') {
                            realkeys.push(el);
                            console.log(realkeys);
                        }
                    })
                    .catch(err => {

                    })
            })

        })
}
/**/

/* 生成 头部导航栏 */
function generateMainheadNav() {
    /* 主体头部导航栏 */
    let menu = ``;
    data.forEach((el, i) => {
        let item = '<div class="item">';
        let item_header = ` 
        <div class="item-header">
            <div></div>
            <h3>
                ${el.title}
                <i>&gt;</i>
            </h3><p>`;
        el.li.forEach((li) => {
            item_header += `<a href="/pages/list.html?title=${li}">${li}</a>`;
        })
        item += item_header + `</p></div>`;

        let item_body = `<div class="item-body"><div><ul>`
        el.subtitle.forEach((subtitle, index) => {
            let sub = `
            <li>
                <div class='item-body-subtitle'>
                    ${subtitle}
                </div>
                <div class='item-body-sublist'>
                `;
            el.sublist[index].forEach((e) => {

                sub += `<a href="/pages/list.html?title=${e}">${e}</a>`
                //getListData(`https://search.jd.com/Search?titleword=${e}enc=utf-8&wq=${e}`, e);
            })
            sub += `</div></li>`
            item_body += sub;

        })
        item_body += `</ul></div></div>`
        item += item_body + '</div>';
        // console.log(item);
        menu += item;
    });
    $('.main-menu').html(menu);
    $(".item-body").map((index, ele) => {
        if (index > 4) {
            $(ele).css("top", "128px");
        }
        if (index == 6) $(ele).css("top", "241px");
    })
}

/* 生成 主体轮大播图 */
function generateMainBigSwiper() {

    /* 主体头部大轮播图 */
    let keys = ["奇异果", "湿巾", "罐头", "调和油", "洗发护理", "饼干蛋糕"]

    console.log();
    $('.mySwiper .swiper-wrapper').html(imagesrc.map((item, i) => {
        return `
        <div class="swiper-slide">
            <a href="/pages/list.html?title=${keys[i]}">
                <img src="${item}" />
            </a>
        </div>`
    }));
    var swiper = new Swiper(".mySwiper", {
        autoplay: {
            delay: 1500
        },
        spaceBetween: 30,
        effect: "fade",
        loop: false,
        navigation: {
            nextEl: ".button-next",
            prevEl: ".button-prev",
        },
        loop: true,
        pagination: {
            el: ".pagination",
            type: "custom",

            renderCustom: function(swiper, current, total) {
                let paginationHtml = '';
                for (let i = 0; i < total; i++) {
                    if (i === (current - 1)) {
                        paginationHtml += `<span class='pagination-bar pagination-bar-on'></span>`;
                    } else {
                        paginationHtml += `<span class='pagination-bar'></span>`
                    }
                }
                return paginationHtml;
            }
        }
    });
    $('.pagination').on('click mouseover', 'span', function() {
        swiper.slideTo($(this).index(), 1000, false);
    })
    $('.mySwiper').hover(function() {
        swiper.autoplay.stop();
    }, function() {
        swiper.autoplay.start();
    })
}
/* 生成 主体头部小轮播图*/
function generateMainLittleSwiper() {
    $('.swiper-little .swiper-wrapper').html(littleImg.map(el => {
        return `
        <div class="swiper-slide">
            <a href="">
                <img src="${el.src}" title="${el.title}">
            </a>
            <a href="">进入&gt;</a>
        </div>
        `;
    }));
    var sswiper = new Swiper(".swiper-little", {
        autoplay: true,
        spaceBetween: 30,
        loop: true,
        effect: "fade",
        pagination: {
            el: ".swiper-little-pagination",
            type: "custom",
            renderCustom: function(swiper, current, total) {
                let paginationHtml = '';
                for (let i = 0; i < total; i++) {
                    if (i === (current - 1)) {
                        paginationHtml += `<span class='little-paginatio-btn little-paginatio-btn-on'></span>`;
                    } else {
                        paginationHtml += `<span class='little-paginatio-btn'></span>`
                    }
                }
                return paginationHtml;
            }
        }
    });
    $('.swiper-little-pagination').on('click mouseover', 'span', function() {
        sswiper.slideTo($(this).index(), 1000, false);
    })

}

/* 生成 超值量贩 */
function generateDiscount(obj) {
    let page = Math.floor(Math.random() * 10);
    pd.getByKey(`_sort=count&_page=${page}&_limit=8`, data => {
        // console.log(res.data);
        $(obj).find(".discount-big").html(data.filter((el, i) => i < 3).map(el => {
            return `
            <div>
                <div class="discount-big-up">
                    <span>
                        <a href="/pages/detial.html?pid=${el.pid}">
                            <img src="${el.imgsrc}" alt="">
                        </a>
                    </span>
                    <span>
                        <a href="/pages/detial.html?pid=${el.pid}" >${el.name}</a>
                        <p>超值量贩定制款</p>
                    </span>
                </div>
                <div class="discount-big-down">
                    <span>量贩价：￥${el.price}</span>
                    <span class="addCart" data-id="${el.pid}"><i></i>加入购物车</span>
                </div>
            </div>
        `;
        })).siblings().find('.list-wrap').html(data.filter((el, i) => i >= 3).map(el => {
            return `
            <span>
                <a href="/pages/detial.html?pid=${el.pid}">
                    <img src="${el.imgsrc}"
                        alt="">
                    <p>${el.name}</p>
                </a>
                <p>${el.shop}</p>
                <p>${el.price}</p>
                <a href="javascript:;" class="addCart" data-id="${el.pid}">
                    <i></i>
                </a>
            </span>
        `;
        }));
    })
}

/* 生成 热销轮播 */
function generateHotList(key) {
    pd.getByKey(`_sort=comments&_order=desc&_limit=36`, data => {
        let str = ""
        for (let i = 0; i < 3; i++) {
            let wrap = `<div class="swiper-slide">`
            for (let j = i * 6; j < i * 6 + 6; j++) {
                // console.log(j);
                wrap += `
                <span>
                    <a href="/pages/detial.html?title=${key}&pid=${data[j].pid}">
                        <img src="${data[j].imgsrc}" alt="">
                    </a>
                    <p class="good-title">${data[j].name}</p>
                    <p class="desc"></p>
                    <p>￥${data[j].price}</p>
                    <a href="javascript:;" class="padd addCart" data-id="${data[j].pid}">
                        <i></i>
                        <span>加入购物车</span>
                    </a>
                </span>
                `;
            }
            str += wrap + '</div>';
        }
        // console.log(str);
        $('.hot-list-swiper .swiper-wrapper').append(str);

        var ssswiper = new Swiper('.hot-list-swiper', {
            autoplay: {
                delay: 2000
            },
            loop: true,
            navigation: {
                nextEl: ".hot-list-next",
                prevEl: ".hot-list-prev",
            }
        });

        $('.hot-list-swiper').hover(() => {
            ssswiper.autoplay.stop();
        }, () => {
            ssswiper.autoplay.start();
        })
    })
}

/* 生成 类别列表 */
function generateCategory(len) {
    /* 获取用户数据 */
    const usrData = JSON.parse(localStorage.getItem('usrData'));
    /* 判断用户是否登录 */
    if (usrData) {
        /* 通过token获取详细数据 */
        ud.getData(`/${encodeURIComponent(usrData.token)}`, data => {
            /* 若已登录 判断favorite是否有数据 无 生成并加载 有 加载 */
            if (data.favorite.length == 0 || data.favorite.length != len) {
                noDataGenerateCategory(len, (keys) => {
                    data.favorite = keys;
                    ud.updateData(`/${encodeURIComponent(usrData.token)}`, data, () => {
                        keys.forEach(key => {
                            /* 获取 */
                            generateCategoryList(key, $('.main'));
                        })
                    })
                })
            } else {
                data.favorite.forEach(key => {
                    /* 获取 */
                    generateCategoryList(key, $('.main'));
                })
            }
        })
    } else {
        /* 若用户未登录直接生成 */
        noDataGenerateCategory(len, (keys) => {
            keys.forEach(key => {
                /* 获取 */
                generateCategoryList(key, $('.main'));
            })
        })
    }
}

/* 若当前用户favorite无数据或长度不匹配 添加 */
function noDataGenerateCategory(len, callback) {
    axios.get('http://localhost:3000/categorys')
        .then(res => {
            // let keys = []
            // for (let i = 0; i < len; i++) {
            //     const key = getRandKey(res.data);
            //     if (keys.indexOf(key) == -1) {
            //         keys.push(key);
            //     } else {
            //         i--;
            //         continue;
            //     }
            // }
            // console.log(res.data.sort(() => Math.random() - 0.5).slice(0, len));
            callback(res.data.sort(() => Math.random() - 0.5).slice(0, len));
        })
}

/* 根据关键字 生成类层 */
function generateCategoryList(key, obj) {
    let str = `
    <div class="main-category">
        <div class="main-mode-head">
            <h3>${key}</h3>
        </div>
        <div class="main-category-bd">
            <div class="category-focus">`;
    pd.getByKey(`category=${key}&_sort=comments&_order=desc&_limit=10`, data => {
        str += ` 
            <a href="javascript:;">
                <img src="${data[0].imgsrc}" alt="">
            </a>
            <div class="category-focus-keys">
        <div>`;
        let focus_keys = {};
        let category_list = ``;
        data.forEach(el => {
            focus_keys[el.title] = 1;
            const b = el.price_plus.length > 0;
            category_list += `
            <li>
                <a href="/pages/detial.html?pid=${el.pid}">
                    <img src="${el.imgsrc}" alt="">
                </a>
                <p class="ptitle">${el.name}</p>
                <div class="price">
                    <p class="pprice">${b?"<del>￥"+el.price+"</del>":'￥'+el.price}</p>
                    <p ${b?"style='display:block'":""}>
                        <em>${b?el.price_plus:""}</em>
                        <i></i>
                    </p>
                </div>
                <a class="padd addCart" data-id=${el.pid}>
                    <i></i>
                    <span>加入购物车</span>
                </a>
            </li>
            
            `;
        })
        for (let key in focus_keys) {
            str += `<a href="/pages/list.html?title=${key}">${key}</a>`;
        }
        str += `
                    </div>
                </div>
            </div>
        <div class="category-list">
            <ul class="list">
        `;
        str += category_list + `
                    </ul>
                </div>
            </div>
        </div>
        `;
        $(obj).append(str);
        $('.addCart').off('click').on('click', function(e) {
            e.preventDefault();
            // console.log($(this).data('id'));
            cd.add($(this).data('id'), (shopping_amount) => {
                $('.mycart .ci-count').text(shopping_amount);
                /* 初始化购物车 */
                hs.render();
            });
            rfb.intoCart($(this).siblings().find('img'), $(this).offset());

        })
        generateFloorNav()
    })
}

/* 生成楼梯 */
function generateFloorNav() {
    let str = ``;
    let arrHei = [];
    /* 
        根据标题生成楼层
        同时获取每层到顶部的值
    */
    $('.main-mode-head h3').each((i, el) => {
        const st = Math.ceil($(el).offset().top);
        // console.log(st);
        str += `<li data-top='${st}'>
            ${$(el).text()}
        </li>`;
        arrHei.push(st);
    })
    /* 初始化楼梯位置 */
    $('.floor-nav').html(str).css('top', $(window).height() / 2 - ($('.floor-nav').height() / 2));
    /* 为楼层添加单击事件 */
    $('.floor-nav li').on('click', function() {
        $('html,body').stop().animate({
            scrollTop: $(this).data('top')
        }, 1000);
    })
    /* 滚动事件 */
    $(window).scroll(function() {
        const minIndex = getMin(Math.ceil($('html').scrollTop()), arrHei);
        if ($('html').scrollTop() > arrHei[0]) {
            $('.floor-nav')
                .fadeIn(500)
                .children()
                .eq(minIndex)
                .addClass('hover')
                .siblings()
                .removeClass('hover')
        } else {
            $('.floor-nav')
                .fadeOut()
        }
    })
}
/* 获取距离最近楼层索引 */
function getMin(n, arr) {
    // let dis = [];
    // arr.forEach(el => {
    //     dis.push(Math.abs(el - n));
    // })
    // return dis.indexOf(Math.min(...dis));
    const dis = arr.map(x => Math.abs(x - n));
    return dis.indexOf(Math.min(...dis));
}




/* 
<div class="main-category">
    <div class="main-mode-head">
        <h3>热卖商品</h3>
    </div>
    <div class="main-category-bd">
        <div class="category-focus">
            <a href="">
                <img src="" alt="">
            </a>
            <div class="category-focus-keys">
                <div>
                    <a href="">早餐奶</a>
                    <a href="">早餐奶</a>
                    <a href="">早餐奶</a>
                    <a href="">早餐奶</a>
                    <a href="">早餐奶</a>
                    <a href="">早餐奶</a>
                </div>
            </div>
        </div>
        <div class="category-list">
            <ul class="list">
                <li>
                    <a href="">
                        <img src="https://img10.360buyimg.com/jdcms/s130x130_jfs/t21712/33/1014083403/259224/51226034/5b1e2ce7N87a40c63.jpg!q80.webp"
                            alt="">
                    </a>
                    <p class="ptitle">三元 利乐枕纯牛奶227ml*16袋/箱</p>
                    <div class="price">
                        <p class="pprice">¥36.00</p>
                        <p>
                            <em></em>
                            <i></i>
                        </p>
                    </div>
                    <a href="" class="padd">
                        <i></i>
                        <span>加入购物车</span>
                    </a>
                </li>
            </ul>
        </div>
    </div>
</div>
*/
/* 添加 */
// function addCart(pid) {
//     let usrData = JSON.parse(localStorage.getItem('usrData'));
//     if (usrData) {
//         // console.log(usrData);
//         axios.get(`http://localhost:3000/usrinfo?token=${usrData.token}`)
//             .then(res => {
//                 let data = res.data[0];
//                 // console.log(data.cartData[pid] != undefined);
//                 data.cartData[pid] = data.cartData[pid] != undefined ? data.cartData[pid] + 1 : 1;
//                 // console.log(data.cartData[pid]);
//                 // console.log(data);
//                 let shopping_amount = Object.keys(data.cartData).length;
//                 axios.put(`http://localhost:3000/usrinfo/${encodeURIComponent(usrData.token)}`, data)
//                     .then(res => {
//                         console.log('添加成功');
//                         console.log(shopping_amount);
//                         $('.mycart .ci-count').text(shopping_amount);
//                         /* 初始化购物车 */
//                         generateMyCart();
//                     })
//                     .catch(err => {
//                         console.log(err + '添加失败');
//                     })
//             })
//     } else {
//         alert('请登录！！')
//     }
// }

/* 删除 */
// function removeCart(pid) {
//     let usrData = JSON.parse(localStorage.getItem('usrData'));
//     axios.get(`http://localhost:3000/usrinfo?token=${usrData.token}`)
//         .then(res => {
//             let data = res.data[0];
//             console.log(data);
//             delete data.cartData[pid];
//             console.log(data);
//             let shopping_amount = Object.keys(data.cartData).length;
//             axios.put(`http://localhost:3000/usrinfo/${encodeURIComponent(usrData.token)}`, data)
//                 .then(res => {
//                     console.log('删除成功');
//                     $('.mycart .ci-count').text(shopping_amount);
//                     /* 初始化购物车 */
//                     generateMyCart();
//                 })
//                 .catch(err => {
//                     console.log(err + '删除失败');
//                 })
//         })
// }


// /* 生成购物车 */
// function generateMyCart() {
//     getCart((data) => {
//         if (data == "err") {
//             $('.mycart .nogoods').html(`
//             <b></b>购物车中还没有商品，赶紧选购吧！
//         `);
//         } else {
//             // console.log(data);
//             let str = ``;
//             data.forEach(el => {
//                 const p = el[1];
//                 str += `
//                 <div class="mycart_item">
//                     <a href="./pages/detial.html?pid=${p.pid}">
//                         <img src="${p.imgsrc}" />
//                     </a>
//                     <p>${p.name}</p>
//                     <span>
//                         ${el[0]}
//                     </span>
//                     <span class="remove_item" data-id="${p.pid}">X</span>
//                 </div>
//                 `;
//             })
//             $('.mycart .nogoods').html(str);
//             $('.mycart .ci-count').text(data.length);
//             $('.remove_item').off('click').on('click', function () {
//                 // console.log($(this).data('id'));
//                 removeCart($(this).data('id'), (shopping_amount) => {
//                     $('.mycart .ci-count').text(shopping_amount);
//                     /* 初始化购物车 */
//                     generateMyCart();
//                 });
//             })

//         }
//     })
// }